package com.ruoyi.web.controller.TiebaPosts.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.web.controller.TiebaForums.domain.TiebaForums;
import com.ruoyi.web.controller.TiebaForums.mapper.TiebaForumsMapper;
import com.ruoyi.web.controller.TiebaPostCollectGuanzhu.domain.TiebaPostCollectGuanzhu;
import com.ruoyi.web.controller.TiebaPostCollectGuanzhu.mapper.TiebaPostCollectGuanzhuMapper;
import com.ruoyi.web.controller.TiebaPosts.domain.TiebaPosts;
import com.ruoyi.web.controller.TiebaPosts.mapper.TiebaPostsMapper;
import com.ruoyi.web.controller.TiebaPosts.service.ITiebaPostsService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * 贴吧里面的帖子Service业务层处理
 *
 * @author yong
 * @date 2025-03-09
 */
@Service
public class TiebaPostsServiceImpl extends ServiceImpl<TiebaPostsMapper, TiebaPosts> implements ITiebaPostsService {

    @Autowired
    private TiebaPostsMapper tiebaPostsMapper;

    @Resource
    private TiebaForumsMapper tiebaForumsMapper;

    @Resource
    private TiebaPostCollectGuanzhuMapper collectGuanzhuMapper;

    /**
     * 查询贴吧里面的帖子列表
     *
     * @param tiebaPosts 贴吧里面的帖子
     * @return 贴吧里面的帖子
     */
    @Override
    public List<TiebaPosts> selectTiebaPostsList(TiebaPosts tiebaPosts) {
        List<TiebaPosts> tiebaPostsList = tiebaPostsMapper.selectList(buildQueryWrapper(tiebaPosts));
        return tiebaPostsList;
    }

    @Override
    public List<TiebaPosts> selectTiebaPostsList2(TiebaPosts tiebaPosts) {
        List<TiebaPosts> tiebaPostsList2 = tiebaPostsMapper.selectList(buildQueryWrapper2(tiebaPosts));
        return tiebaPostsList2;
    }

    @Override
    public List<TiebaPosts> selectTiebaPostsList3(TiebaPosts tiebaPosts) {
        List<TiebaPosts> tiebaPostsList3 = tiebaPostsMapper.selectList(buildQueryWrapper3(tiebaPosts));
        return tiebaPostsList3;
    }




    private LambdaQueryWrapper<TiebaPosts> buildQueryWrapper(TiebaPosts query) {
        Map<String, Object> params = query.getParams();
        LambdaQueryWrapper<TiebaPosts> lqw = Wrappers.lambdaQuery();
        lqw.eq(query.getForumId() != null, TiebaPosts::getForumId, query.getForumId());
        lqw.eq(query.getUserId() != null, TiebaPosts::getUserId, query.getUserId());
        lqw.eq(query.getDeptId() != null, TiebaPosts::getDeptId, query.getDeptId());
        lqw.eq(StringUtils.isNotBlank(query.getTitle()), TiebaPosts::getTitle, query.getTitle());
        lqw.eq(StringUtils.isNotBlank(query.getContent()), TiebaPosts::getContent, query.getContent());
        lqw.eq(StringUtils.isNotBlank(query.getImageUrl()), TiebaPosts::getImageUrl, query.getImageUrl());
        lqw.eq(query.getCommentCount() != null, TiebaPosts::getCommentCount, query.getCommentCount());
        lqw.eq(query.getLoveCount() != null, TiebaPosts::getLoveCount, query.getLoveCount());
        lqw.eq(query.getShareCount() != null, TiebaPosts::getShareCount, query.getShareCount());
        lqw.orderByDesc(TiebaPosts::getCreateTime);
        return lqw;
    }


    private LambdaQueryWrapper<TiebaPosts> buildQueryWrapper2(TiebaPosts query) {
        LambdaQueryWrapper<TiebaPosts> lqw = Wrappers.lambdaQuery();

        // userId 必须存在
//        if (query.getUserId() != null) {
//            lqw.eq(TiebaPosts::getUserId, query.getUserId()); // 确保使用字段引用
//        } else {
//            throw new IllegalArgumentException("userId 不能为空"); // 抛出异常，确保 userId 不为空
//        }

        // forumId 可以为空，只有在不为空时才添加查询条件
        if (query.getForumId() != null) {
            lqw.like(TiebaPosts::getForumId, query.getForumId()); // 确保使用字段引用
        }


        return lqw;
    }

    private LambdaQueryWrapper<TiebaPosts> buildQueryWrapper3(TiebaPosts query) {
        LambdaQueryWrapper<TiebaPosts> lqw = Wrappers.lambdaQuery();
        lqw.like(TiebaPosts::getForumId, query.getForumId()); // 确保使用字段引用
        return lqw;
    }


    @Transactional
    @Override
    public boolean toggleAction(Long userId, Long postId, Integer actionType) {
        // 参数校验
        if (!Arrays.asList(1, 2).contains(actionType)) {
            throw new IllegalArgumentException("非法操作类型");
        }

        // 查询帖子信息
        TiebaPosts post = tiebaPostsMapper.selectById(postId);
        if (post == null) throw new RuntimeException("帖子不存在");

        // 查询现有记录
        TiebaPostCollectGuanzhu relation = collectGuanzhuMapper.selectOne(
                new LambdaQueryWrapper<TiebaPostCollectGuanzhu>()
                        .eq(TiebaPostCollectGuanzhu::getUserId, userId)
                        .eq(TiebaPostCollectGuanzhu::getPostId, postId)
                        .eq(TiebaPostCollectGuanzhu::getForumType, actionType)
        );

        // 原子操作计数器
        if (relation != null) {
            return handleCancel(post, actionType, relation.getId());
        } else {
            return handleAdd(post, userId, actionType);
        }
    }

    private boolean handleCancel(TiebaPosts post, Integer actionType, Long relationId) {
        // 删除关系记录
        collectGuanzhuMapper.deleteById(relationId);

        // 更新计数器
        String postColumn = actionType == 1 ? "guanzhu_count" : "collect_count";
        String postSql = postColumn + " = GREATEST(" + postColumn + " - 1, 0)";

        // 更新帖子计数
        tiebaPostsMapper.update(null, new UpdateWrapper<TiebaPosts>()
                .eq("id", post.getId())
                .setSql(postSql));

        // 关注操作需要更新贴吧计数
        if (actionType == 1) {
            tiebaForumsMapper.update(null, new UpdateWrapper<TiebaForums>()
                    .eq("id", post.getForumId())
                    .setSql("guanzhu_count = GREATEST(guanzhu_count - 1, 0)"));
        }
        return false;
    }

    private boolean handleAdd(TiebaPosts post, Long userId, Integer actionType) {
        // 创建新记录
        TiebaPostCollectGuanzhu newRelation = new TiebaPostCollectGuanzhu()
                .setUserId(userId)
                .setPostId(post.getId())
                .setForumType(actionType)
                .setDeptId(post.getDeptId());

        if (collectGuanzhuMapper.insert(newRelation) <= 0) {
            throw new RuntimeException("操作失败");
        }

        // 更新计数器
        String postColumn = actionType == 1 ? "guanzhu_count" : "collect_count";

        // 更新帖子计数
        tiebaPostsMapper.update(null, new UpdateWrapper<TiebaPosts>()
                .eq("id", post.getId())
                .setSql(postColumn + " = " + postColumn + " + 1"));

        // 关注操作需要更新贴吧计数
        if (actionType == 1) {
            tiebaForumsMapper.update(null, new UpdateWrapper<TiebaForums>()
                    .eq("id", post.getForumId())
                    .setSql("guanzhu_count = guanzhu_count + 1"));
        }
        return true;
    }

}
